package com.trainoo.mina.handler;

import com.trainoo.mina.codec.MessagePack;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;

/**
 * @Auther: zt
 * @Date: 2020/4/13 17:28
 * @Description:
 */
public class MyServerHandler extends IoHandlerAdapter {

    private static final Logger LOG = LoggerFactory.getLogger(MyServerHandler.class);

    public MyServerHandler() {
        super();
    }

    @Override
    public void sessionCreated(IoSession session) throws Exception {
        LOG.info("服务端与客户端连接成功,sessionId={}", session.getId());
    }

    @Override
    public void sessionOpened(IoSession session) throws Exception {
        LOG.info("服务端与客户端连接打开,sessionId={}", session.getId());
    }

    @Override
    public void sessionClosed(IoSession session) throws Exception {
        LOG.info("服务端与客户端连接关闭,sessionId={}", session.getId());
    }

    @Override
    public void sessionIdle(IoSession session, IdleStatus status) throws Exception {
        LOG.info("服务端[{}]进入空闲状态，idleStatus={}", session.getId(), status.toString());
    }

    @Override
    public void exceptionCaught(IoSession session, Throwable cause) throws Exception {
        LOG.error("服务端发生异常", cause);
    }

    @Override
    public void messageReceived(IoSession session, Object message) throws Exception {
        LOG.info("服务端接受到来自[{}]消息：{}", session.getId(), message);
        if (message.equals("exit")) {
            session.close(true); // 如果接收到exit，则退出程序
        }
        // Date date = new Date();
        // session.write(date);
        session.write(new MessagePack(new Date().toString()));
    }

    @Override
    public void messageSent(IoSession session, Object message) throws Exception {
        LOG.info("服务端发送消息成功：" + message);
    }

    @Override
    public void inputClosed(IoSession session) throws Exception {
        LOG.info("session[{}]输入关闭", session.getId());
        session.close(true);
    }
}
